package com.example.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.entity.*;
import com.example.mapp.PointFlowMapp;
import com.example.util.DateUtils;
import com.example.util.SystemPointUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.example.ext.entity.ExtElevatorAppraisal;
import com.example.mapp.ElevatorAppraisalMapp;
import com.example.mapp.ElevatorMapp;
import com.example.mapp.PromotionMapp;
import com.example.service.ElevatorAppraisalService;
import com.example.util.PromotionUtil;
import com.example.util.ResultUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import ch.qos.logback.classic.Logger;

/**
 * Created by simon on 2017/10/20.
 */
@Service
public class ElevatorAppraisalServiceImpl implements ElevatorAppraisalService {

    private final static Logger logger = (Logger) LoggerFactory.getLogger(ElevatorAppraisalServiceImpl.class);


    @Autowired
    ElevatorAppraisalMapp elevatorAppraisalMapp;

    @Autowired
    ElevatorMapp elevatorMapp;

	@Autowired
	private PromotionMapp promotionMapp;

    @Autowired
    private PointFlowMapp pointFlowMapp;

    @Override
    public Map<String, Object> queryListById(ExtElevatorAppraisal extElevatorAppraisal) {
        List<ElevatorAppraisal> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtElevatorAppraisal> page = PageHelper.startPage(extElevatorAppraisal.getCurrentPage(), extElevatorAppraisal.getPageSize());
            list = elevatorAppraisalMapp.queryListById(extElevatorAppraisal);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    @Override
    public Map<String, Object> queryListByPartyId(ExtElevatorAppraisal extElevatorAppraisal) {
        List<ExtElevatorAppraisal> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtElevatorAppraisal> page=PageHelper.startPage(extElevatorAppraisal.getCurrentPage(), extElevatorAppraisal.getPageSize());
            list=elevatorAppraisalMapp.queryListByPartyId(extElevatorAppraisal);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    @Override
    @Transactional
    public Map<String, Object> add(Map<String, Object> elevatorAppraisal) {
        try{
            int i = elevatorAppraisalMapp.add(elevatorAppraisal);
            if((elevatorAppraisal.get("isLike")+"").equals("1")){
               String elevatorId = elevatorAppraisal.get("elevatorId")+"";
                elevatorMapp.updateLikeNum(elevatorId);
            }
//            if ("2".equals(elevatorAppraisal.get("evaluateType") + "")) {
//				Elevator elevator = elevatorMapp.queryById(elevatorAppraisal.get("elevatorId") + "");
//				if (null != elevator && null != elevator.getSafeUserId()) {
//					Map<String, Object> map = new HashMap<>();
//					map.put("type", "3");
//					map.put("userId", elevator.getSafeUserId());
//					Promotion promotion = promotionMapp.findById(map);
//					if (null != promotion && promotion.getId() != null) {
//						promotion = PromotionUtil.calc(promotion, "3", -50, false);
//						promotionMapp.update(promotion);
//					} else {
//						promotion = new Promotion();
//						promotion.setType("3");
//						promotion.setUserId(elevator.getSafeUserId().toString());
//						promotion = PromotionUtil.calc(promotion, "3", -50, true);
//						promotionMapp.insert(promotion);
//					}
//					PromotionRecord promotionRecord = new PromotionRecord();
//					promotionRecord.setUserId(promotion.getUserId());
//					promotionRecord.setType(promotion.getType());
//					promotionRecord.setEmpiricItem("接到乘客APP投诉");
//					promotionRecord.setAddedTime(PromotionUtil.getTime());
//					promotionRecord.setEmpiricValue(-50);
//					promotionMapp.insertRecord(promotionRecord);
//					if (null != elevator.getUsedPartyId()) {
//						PromotionUtil.calcParty(promotionMapp, -550, "2", elevator.getUsedPartyId());
//						PromotionRecord promotionRecord1 = new PromotionRecord();
//						promotionRecord1.setUserId(String.valueOf(elevator.getUsedPartyId()));
//						promotionRecord1.setType("2");
//						promotionRecord1.setEmpiricItem("接到乘客APP投诉");
//						promotionRecord1.setAddedTime(PromotionUtil.getTime());
//						promotionRecord1.setEmpiricValue(-550);
//						promotionMapp.insertRecord(promotionRecord1);
//					}
//					if (null != elevator.getMaintenancePartyId()) {
//						PromotionUtil.calcParty(promotionMapp, -500, "1", elevator.getMaintenancePartyId());
//						PromotionRecord promotionRecord1 = new PromotionRecord();
//						promotionRecord1.setUserId(String.valueOf(elevator.getMaintenancePartyId()));
//						promotionRecord1.setAddedTime(PromotionUtil.getTime());
//						promotionRecord1.setType("1");
//						promotionRecord1.setEmpiricItem("接到乘客APP投诉");
//						promotionRecord1.setEmpiricValue(-550);
//						promotionMapp.insertRecord(promotionRecord1);
//					}
//				}
//            }
        }catch (Exception e){
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError("提交失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("提交成功",null);
    }

    @Override
    @Transactional
    public Map<String, Object> updateFeedBack(ElevatorAppraisal elevatorAppraisal1) {
        try{
            elevatorAppraisalMapp.updateFeedBack(elevatorAppraisal1);
			/*ElevatorAppraisal elevatorAppraisal = elevatorAppraisalMapp.queryById(elevatorAppraisal1.getId()+"");
            String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());*/
            /*int time = PromotionUtil.calcDate(date, elevatorAppraisal.getAppraisalTime(), "2");*/
            /*Integer empiricValue = 0;
            if (0 == time) {
            	empiricValue = 10;
            } else if (1 == time) {
            	empiricValue = 8;
            }  else if (2 == time) {
            	empiricValue = 5;
            } else {
            	empiricValue = 1;
            }*/
            /*if ("1".equals(elevatorAppraisal.getIsFeedBack())) {
            	Elevator elevator = elevatorMapp.queryById(elevatorAppraisal.getElevatorId());
				*//*if (null != elevator && null != elevator.getSafeUserId()) {
					*//**//*Map<String, Object> map = new HashMap<>();
					map.put("type", "3");
					map.put("userId", elevator.getSafeUserId());
					Promotion promotion = promotionMapp.findById(map);*//**//*
					*//**//*if (null != promotion && promotion.getId() != null) {
						promotion = PromotionUtil.calc(promotion, "3", empiricValue, false);
						promotionMapp.update(promotion);
					} else {
						promotion = new Promotion();
						promotion.setType("3");
						promotion.setUserId(elevator.getSafeUserId().toString());
						promotion = PromotionUtil.calc(promotion, "3", empiricValue, true);
						promotionMapp.insert(promotion);
					}*//**//*
					*//**//*PromotionRecord promotionRecord = new PromotionRecord();
					promotionRecord.setUserId(promotion.getUserId());
					promotionRecord.setType(promotion.getType());
					promotionRecord.setEmpiricItem("回复1条乘客评价（包括点赞和反馈）");
					promotionRecord.setAddedTime(PromotionUtil.getTime());
					promotionRecord.setEmpiricValue(empiricValue);
					promotionMapp.insertRecord(promotionRecord);*//**//*
				}*//*
            }*/
        }catch (Exception e){
        	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError("提交失败"+e.getMessage(),null);
        }finally {
            // 当已回复的状态
            if ("1".equals(elevatorAppraisal1.getIsFeedBack()) && elevatorAppraisal1.getRoleId() ==5 ) {
                try {
                    // 用户获取时间
                    ElevatorAppraisal appraisal = elevatorAppraisalMapp.queryById(elevatorAppraisal1.getId().toString());
                    Date date = DateUtils.parseDate(appraisal.getAppraisalTime(), "yyyyMMddHHmmss");
                    Date nowDate = DateUtils.parseDate(DateUtils.formatDate(new Date(), "yyyyMMddHHmmss"), "yyyyMMddHHmmss");
                    long hours = DateUtils.getHoursTwoDate(date, nowDate);
                    if(hours<=72){
                        // 获取分数
                        PointDefendInfoCache infoCache = new PointDefendInfoCache();
                        PointDefend defend = new PointDefend();
                        if(hours>=0 && hours<=24){
                            // 得到10分
                            defend = infoCache.getKeyByValue("reply_feedback_day");
                        }else if(hours>24 && hours<=72){
                            defend = infoCache.getKeyByValue("reply_feedback_three_day");
                        }

                        // 获取当前用户，计算积分
                        Map<String, Object> maps = pointFlowMapp.findUserInfoByUserId(elevatorAppraisal1.getUserId());
                        long mark = (long) maps.get("mark");
                        int round = (int) (mark + defend.getMark());
                        // 更新用户信息总积分
                        String userId = maps.get("userId").toString();
                        int i1 = pointFlowMapp.updateMark(round, userId);

                        String userName = maps.get("userName").toString();
                        String partyName = maps.get("partyName").toString();
                        SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, "回复反馈投诉");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ResultUtil.returnSuccess("提交成功",null);
    }

	@Override
	public Map<String, Object> good(Map<String, Object> elevatorAppraisal) {
		try {
			if((elevatorAppraisal.get("isLike")+"").equals("1")){
				String elevatorId = elevatorAppraisal.get("elevatorId")+"";
				elevatorMapp.updateLikeNum(elevatorId);
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("查询失败"+e.getMessage(),null);
		}
		return ResultUtil.returnSuccess("查询成功",null);
	}
}
